﻿using System;
using System.Runtime.InteropServices;
using System.Text;


namespace ESCAPI_WRAPPER
{
    [StructLayout(LayoutKind.Sequential)]
    public struct SimpleCapParams
    {
        public IntPtr mTargetBuf; // Must be at least mWidth * mHeight * sizeof(int) of size! 
        public int mWidth;  // Buffer width 
        public int mHeight;  // Buffer height 

        public SimpleCapParams(int wid, int hei)
        {
            mWidth = wid;
            mHeight = hei;
            mTargetBuf = System.Runtime.InteropServices.Marshal.AllocHGlobal(wid * hei * sizeof(int) );
            
        }

        public void freeMem()
        {
            if (mTargetBuf != IntPtr.Zero) System.Runtime.InteropServices.Marshal.FreeHGlobal(mTargetBuf);
        }
    };

    


    public static class Escapi
    {

        public static int setupESCAPI()
        {
            if (ESCAPIDLLVersion() != 0x200) throw new Exception("expected ESCAPIDLLVersion 0x200, using wrong escapi DLL ? ");

            initCOM();

            return countCaptureDevices();
        }

        [DllImport("escapi")]
        public static extern int countCaptureDevices();
        [DllImport("escapi")]
        public static extern int initCapture(uint deviceno, ref SimpleCapParams aParams);
        [DllImport("escapi")]
        public static extern void deinitCapture(uint deviceno);
        [DllImport("escapi")]
        public static extern void doCapture(uint deviceno);
        [DllImport("escapi")]
        public static extern int isCaptureDone(uint deviceno);
        [DllImport("escapi")]
        public static extern void initCOM();
        [DllImport("escapi")]
        public static extern void getCaptureDeviceName(uint deviceno, StringBuilder namebuffer, int bufferlength);
        [DllImport("escapi")]
        public static extern int ESCAPIDLLVersion();

        public static string getCaptureDeviceName(uint deviceno)
        {
            StringBuilder sb = new StringBuilder(256);
            Escapi.getCaptureDeviceName(deviceno, sb, sb.Capacity);
            return sb.ToString();
        }

        [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
        public static extern IntPtr MemCopy(IntPtr dest, IntPtr src, uint count);
    };

}